package com.lj.cloudDisk.config.exception;


import com.lj.cloudDisk.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public R error(Exception e) {
        System.out.println(e);
        return R.error().message("执行了全局异常处理...");
    }

    @ResponseBody
    @ExceptionHandler(ArithmeticException.class)
    public R error(ArithmeticException e) {
        return R.error().message("执行了ArithmeticException异常处理...");
    }

    @ResponseBody
    @ExceptionHandler(SpaceException.class)
    public R error(SpaceException e) {
        log.error(e.getMessage());//写进指定文件中
        return R.error().code(e.getCode()).message(e.getMsg());
    }

    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public  R error(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        ArrayList<String> errors = new ArrayList<>();
        bindingResult.getFieldErrors().stream().forEach(
                item->{
                    errors.add(item.getDefaultMessage());
                }
        );
        String errMessage = StringUtils.join(errors,",");
        //记录异常
        log.error("异常信息：{}",errMessage);
        return R.error().message(errMessage);
    }
}
